local LB_U = require "packages.lb_kill_utility.utility"

local skel = fk.CreateSkill {
  name = "lb_zero__zhuipu",
  tags = {LB_U.WaxneSkill},
  max_branches_use_time = function (self, player)
    return {
      ["round"] = {
        [Player.HistoryRound] = #LB_U.getWanedEffect(player, "lb_zero__zhuipu", LB_U.isWaned(player, "lb_zero__zhuipu"))
      }
    }
  end,
  dynamic_desc = function (self, player, lang)
    local status = LB_U.isWaned(player, "lb_zero__zhuipu") and "<font color=\"yellow\">（已成玦）</font>" or ""
    local branch = LB_U.isWaned(player, "lb_zero__zhuipu") and "" or "<b><a href='lb_waxne_skill'><font color='red'>成玦</font></a></b>:若你获得过所有项的效果，你获得<a href=':lb_zero__youzhi'><font color='red'>〖犹执〗</font></a>。"
    local desc = ""
    local list = {}
    local choices = {"targetplus1", "bypasstimes", "damageplus1"}
    for i, effect in ipairs(LB_U.getWanedEffect(player, "lb_zero__zhuipu")) do
      local text = tostring(i) .. Fk:translate(choices[effect])
      if not LB_U.isWanedEffect(player, "lb_zero__zhuipu", effect) then
        text = "<s>".. text .."</s>"
      end
      table.insert(list, text)
    end
    desc = table.concat(list, "；")
    return "<b><a href='lb_waxne_skill'><font color='red'>溯月技</font></a></b>"..status.."，你不因使用一次失去至少两张牌后，你可以展示之并摸一张牌，本回合你使用牌时执行第X项（X为其中花色数）：".. desc ..branch
  end,
}

Fk:loadTranslationTable{
  ["lb_zero__zhuipu"] = "缀圃",
  [":lb_zero__zhuipu"] = "<b><a href='lb_waxne_skill'><font color='red'>溯月技</font></a></b>，你不因使用一次失去至少两张牌后，你可以展示之并摸一张牌，本回合你使用牌时执行第X项（X为其中花色数）：1.最大目标数+1；"..
  "2.无次数限制；3.首次造成伤害+1。<b><a href='lb_waxne_skill'><font color='red'>成玦</font></a></b>:若你获得过所有项的效果，你获得<a href=':lb_zero__youzhi'><font color='red'>〖犹执〗</font></a>。",

  ["@[lb_zero__zhuipu]lb_zero__zhuipu"] = "缀圃", --白色：未发动；绿色：正在生效；黄色：已经删除
  ["#lb_zero__zhuipu-choose"] = "缀圃：你可以为此%arg增加1个目标",
  ["#lb_zero__zhuipu-choice"] = "缀圃：技能成玦，请选择一项保留",
  ["targetplus1"] = "目标上限+1",
  ["bypasstimes"] = "无次数限制", 
  ["damageplus1"] = "首次造成伤害+1",

  ["$lb_zero__zhuipu1"] = "你身上的味道，我很喜欢哦。",
  ["$lb_zero__zhuipu2"] = "呀吼，你的席德出现啦。",
}

Fk:addQmlMark{
  name = skel.name,
  how_to_show = function (name, value, player)
    if type(value) ~= "table" or #value == 0 then return " " end
    local numtable = {"①", "②", "③"}
    return table.concat(table.map(value, function (num)
      local color = "white"
      if LB_U.isWanedEffect(player, skel.name, num) then
        if table.contains(player:getTableMark(skel.name .. "-turn"), num) then
          color = "green"
        end
      else
        color = "yellow"
      end
      return "<font color='"..color.."'>"..numtable[num].."</font>"
    end))
  end,
}

skel:addEffect(fk.AfterCardsMove, {
  anim_type = "support",
  times = function (self, player)
    local num = #LB_U.getWanedEffect(player, skel.name, LB_U.isWaned(player, skel.name)) - player:usedSkillTimes(skel.name, Player.HistoryRound, "round")
    return math.max(0, num)
  end,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and skel:withinBranchTimesLimit(player, "round", Player.HistoryRound) then
      for _, move in ipairs(data) do
        if move.moveReason ~= fk.ReasonUse and #move.moveInfo > 1 and move.from == player and (move.to ~= player or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
          return true
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    player:addSkillBranchUseHistory(skel.name, "round")
    local cards = {}
    local suits = {}
    for _, move in ipairs(data) do
      if move.moveReason ~= fk.ReasonUse and #move.moveInfo > 1 and move.from == player and (move.to ~= player or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
        for _, info in ipairs(move.moveInfo) do
          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) then
            table.insert(cards, info.cardId)
            table.insertIfNeed(suits, Fk:getCardById(info.cardId).suit)
          end
        end
      end
    end
    player:showCards(cards)
    if player.dead then return end
    player:drawCards(1, skel.name)
    if player.dead then return end
    for i, effect in ipairs(LB_U.getWanedEffect(player, skel.name, true)) do
      if i == #suits and LB_U.isWanedEffect(player, skel.name, effect) then
        player.room:addTableMarkIfNeed(player, skel.name, effect)
        player.room:addTableMarkIfNeed(player, skel.name.."-turn", effect)
        break
      end
    end
    if not (skel:withinBranchTimesLimit(player, "round", Player.HistoryRound) or LB_U.isWaned(player, skel.name)) then
      player.room.logic:trigger(LB_U.SkillCrescent, player, { skill = Fk.skills[skel.name], who = player, reason = "cycle" })
    end
  end,
})

skel:addEffect(LB_U.SkillCrescent, {
  anim_type = "big",
  is_delay_effect = true,
  can_trigger = function (self, event, target, player, data)
    return target == player and data.skill.name == skel.name and player:hasSkill(skel.name)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local choices = {"targetplus1", "bypasstimes", "damageplus1"}
    local choice = room:askToChoice(player, {
      choices = choices,
      skill_name = skel.name,
      prompt = "#lb_zero__zhuipu-choice",
    })
    LB_U.setWaned(player, skel.name, table.indexOf(choices, choice))
    if #player:getTableMark(skel.name) == 3 then
      room:handleAddLoseSkills(player, "lb_zero__youzhi", nil, true, false)
    end
  end,
})

skel:addEffect(fk.CardUsing, {
  anim_type = "offensive",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if data.card and target == player then
      local list = table.filter(LB_U.getWanedEffect(player, skel.name, true), function (num)
        return table.contains(player:getTableMark(skel.name .. "-turn"), num)
      end)
      if #list > 0 then
        event:setCostData(self, {list = list})
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local list = event:getCostData(self).list
    if table.contains(list, 1) then
      if #data:getExtraTargets() > 0 then
        local tos = player.room:askToChoosePlayers(player, {
          min_num = 1,
          max_num = 1,
          targets = data:getExtraTargets(),
          skill_name = skel.name,
          prompt = "#lb_zero__zhuipu-choose:::"..data.card:toLogString(),
          cancelable = true,
        })
        if #tos > 0 then
          for _, p in ipairs(tos) do
            data:addTarget(p)
          end
        end
      end
    end
    if table.contains(list, 2) then
      if not data.extraUse then
        data.from:addCardUseHistory(data.card.trueName, -1)
        data.extraUse = true
      end
    end
    if table.contains(list, 3) then
      data.extra_data = data.extra_data or {}
      data.extra_data.lb_zero__zhuipudamageplus = true
    end
  end,
})

skel:addEffect(fk.DamageInflicted, {
  anim_type = "offensive",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if data.card == nil or target ~= player then return false end
    local room = player.room
    local card_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if not card_event then return false end
    local use = card_event.data
    return use.extra_data and use.extra_data.lb_zero__zhuipudamageplus and use.extra_data.lb_zero__zhuipudamageplus == true
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if not card_event then return false end
    local use = card_event.data
    use.extra_data.lb_zero__zhuipudamageplus = {}
    data:changeDamage(1)
  end,
})


skel:addAcquireEffect(function (self, player, is_start)
  LB_U.setWanedEffect(player, skel.name, 3, "@[lb_zero__zhuipu]lb_zero__zhuipu")
end)

skel:addLoseEffect(function (self, player, is_death)
  player.room:setPlayerMark(player, skel.name, 0)
  player.room:setPlayerMark(player, skel.name .. "-turn", 0)
  LB_U.setWanedEffect(player, skel.name, nil, "@[lb_zero__zhuipu]lb_zero__zhuipu")
end)

return skel
